package com.tencent.wuyanzu.whattoeat;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.provider.Settings;

import com.tencent.wuyanzu.whattoeat.Global.ARGS;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;

public class GroupActivity extends Activity{

    WebSocketClient client;
    Fragment joinGroupFragment,startGroupFragment,voteFragment,fragmentNow;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group);
        try {
            client=new WebSocketClient(new URI("ws://115.159.31.240:8080/Chapter2/ws/group")) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                }

                @Override
                public void onMessage(String s) {
                    try {
                        JSONObject json=new JSONObject(s);
                        switch ((int)json.get("status")){
                            //0: 未开始
                            case 0:{
                                if(ARGS.UID==(int)json.get("leaderID")){
                                    if(fragmentNow instanceof JoinGroupFragment){
                                        //接下来进入等待用户加入界面
                                        startGroupFragment=StartGroupFragment.newInstance(client,json.getInt("groupID"));
                                        fragmentNow=startGroupFragment;
                                        getFragmentManager().beginTransaction().replace(R.id.groupContent,fragmentNow);
                                    }
                                    else if(fragmentNow instanceof StartGroupFragment){
                                        //刷新人数
                                    }
                                }
                            }break;
                            //1: 已开始
                            case 1:;break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {

                }
            };
            joinGroupFragment=JoinGroupFragment.newInstance(client);
            voteFragment=VoteFragment.newInstance(client);
            fragmentNow=joinGroupFragment;
            getFragmentManager().beginTransaction().replace(R.id.groupContent,fragmentNow);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

}
